package com.xzzz.common.iaas.alibaba.sms;

import cn.hutool.core.util.StrUtil;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.xzzz.common.base.exception.XzException500;
import com.xzzz.common.base.util.json.JsonUtil;
import com.xzzz.common.iaas.IaasProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 阿里云短信服务接口
 *
 * @author xzzz
 *
 */
@Slf4j
@Component
public class AliSmsManager {

    private static final String SYS_DOMAIN = "dysmsapi.aliyuncs.com";
    private static final String SYS_ACTION = "SendSms";
    private static final String SYS_VERSION = "2017-05-25";

    private static final String QUERY_PARAM_REGION_ID = "cn-hangzhou";
    private static final String QUERY_PARAM_SIGN_NAME = "测试";

    private static final String ACCESS_KEY_ID = "LTAI4G2jfv22NdmrEdcjcnz8";
    private static final String SECRET = "ITPSlEPynE0vM6t3eiYHgiWDRdx43h";

    private IAcsClient client;

    public static void main(String[] args) {

    }

    public AliSmsManager(IaasProperties prop) {
        DefaultProfile profile = DefaultProfile.getProfile(QUERY_PARAM_REGION_ID, ACCESS_KEY_ID, SECRET);
        client = new DefaultAcsClient(profile);
    }

    /**
     * 发送消息
     *
     * @param msg      消息体
     * @param template 模板ID
     */
    public void send(PhoneMsgReq msg) {
        try {
            CommonRequest request = commonRequestBuilder(msg);
            CommonResponse response = client.getCommonResponse(request);
            String body = response.getData();
            AliMsgRes resp = JsonUtil.toObj(body, AliMsgRes.class);
            log.debug("[阿里短信] 响应内容: {}", body);
            // 校验响应结果
            if (resp == null || resp.getCode() == null || !AliMsgResultEnum.OK.getCode().equals(resp.getCode())) {
                if (resp != null && StrUtil.isNotBlank(resp.getCode())) {
                    log.error("[阿里短信] 发送短信失败,内容: {},错误信息: {}", msg.toString(), resp.getMessage());
                    String errorMsg = AliMsgResultEnum.getSimpleMessageByCode(resp.getCode());
                    throw new XzException500((StrUtil.isNotBlank(errorMsg) ? errorMsg : AliMsgResultEnum.getMessageByCode(resp.getCode())));
                } else {
                    log.error("[阿里短信] 发送短信失败,内容: {},错误信息: {}", msg.toString(), "未知错误");
                    throw new XzException500("发送短信时发生未知错误");
                }
            }
        } catch (ClientException e) {
            e.printStackTrace();
            log.error("[阿里短信] 发送短信时异常,内容: {},错误信息: {}", msg.toString(), e.getMessage());
            throw new XzException500("发送短信时异常");
        }
    }

    /**
     * 构建短信请求 request
     *
     * @param msg 短信信息
     * @return 短信 request
     */
    private static CommonRequest commonRequestBuilder(PhoneMsgReq msg) {
        log.info("[阿里短信] 发送: 手机号:{}, 类型:{}, 内容: {}", msg.getReceiverPhone(), msg.getTemplate(), msg.getContent());
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(SYS_DOMAIN);
        request.setSysAction(SYS_ACTION);
        request.setSysVersion(SYS_VERSION);

        request.putQueryParameter("RegionId", QUERY_PARAM_REGION_ID);
        // 签名
        request.putQueryParameter("SignName", QUERY_PARAM_SIGN_NAME);
        // 模板 ID
        request.putQueryParameter("TemplateCode", msg.getTemplate());
        // 手机号
        request.putQueryParameter("PhoneNumbers", msg.getReceiverPhone());
        // 模板参数 json 字符串
        request.putQueryParameter("TemplateParam", msg.getContent());
        // 外部业务 ID
        request.putQueryParameter("OutId", msg.getId());

        return request;
    }
}
